package com.blb.exam.student.controller;

import com.alibaba.fastjson.JSON;
import com.blb.exam.common.controller.BaseServlet;
import com.blb.exam.common.entity.ExamRecord;
import com.blb.exam.common.entity.Quetion;
import com.blb.exam.common.entity.QuetionSet;
import com.blb.exam.common.entity.User;
import com.blb.exam.common.util.SpringUtils;
import com.blb.exam.student.service.ExamRecordService;
import com.blb.exam.student.service.QuetionService;
import com.blb.exam.student.service.QuetionSetService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@WebServlet("/examRecord.do")
public class ExamRecordServlet extends BaseServlet {

    private ExamRecordService examRecordService = SpringUtils.getBean(ExamRecordService.class);

    public void findByUserId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        User user = (User) req.getSession().getAttribute("user");
        List<ExamRecord> records = examRecordService.findByUserId(user.getId());
        req.setAttribute("records", records);
        req.getRequestDispatcher("examRecord.jsp").forward(req,resp);
    }

    public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String record = req.getParameter("record");
        //解析JSON
        ExamRecord examRecord = JSON.parseObject(record, ExamRecord.class);
        //获得session中的userId
        User user = (User) req.getSession().getAttribute("user");
        examRecord.setUserId(user.getId());
        //设置当前时间
        examRecord.setExamDate(LocalDateTime.now());
        //添加考试记录
        examRecordService.addExamRecord(examRecord);
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().print("ok");
    }
}
